package cn.xiaolang.function.network.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO
 *
 * @author Dean
 * @date 2022-01-26
 */
public class SocketServerBIO {

    public static void main(String[] args) throws IOException {
        //定义一个服务端对象，并指定服务端的接口
        int port = 10010;
        ServerSocket server = new ServerSocket(port);
        System.out.println("server up use port: " + port);

        //当有客户端要连接的时候，一直接受连接
        while (true) {
            Socket s = server.accept();
            new Thread(() -> {
                //获取连接到的客户端
                System.out.println(s.getRemoteSocketAddress().toString() + " connected! ");
                try {
                    //定义一个字符输入流缓冲区对象，用来读取从客户端发来的字节流数据
                    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        System.out.println("[client] " + s.getInetAddress().getHostAddress() + " send data: " + line);
                        if (line.equals("over")) {
                            s.close();
                            break;
                        }
                        //向客户端回复的数据
                        OutputStream out = s.getOutputStream();
                        out.write(line.toUpperCase().getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
